﻿layui.use(['form', 'layer', 'laydate', 'table'], function () {
    var form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate,
        table = layui.table;

    //列表
    var tableIns = table.render({
        elem: '#userList',
        url: '/admin/user/list',
        cellMinWidth: 95,
        method: 'post',
        page: true,
        limit: 20,
        limits: [10, 15, 20, 30, 50, 100],
        id: "userListTable",
        where: {
            userState: $('#enable').val(),
            expire: $('#expire').val(),
            userName: $('#txtUserName').val()
        },
        request: {
            pageName: 'pageIndex' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        response: {
            statusName: 'Code' //规定数据状态的字段名称，默认：code
            , statusCode: 1 //规定成功的状态码，默认：0
            , msgName: 'Msg' //规定状态信息的字段名称，默认：msg
            , countName: 'Count' //规定数据总数的字段名称，默认：count
            , dataName: 'Data' //规定数据列表的字段名称，默认：data
        },
        cols: [[
            { type: "checkbox", fixed: "left", width: 60 },
            { field: 'UserName', title: '用户名', align: "center" },
            { field: 'Code', title: '验证码', align: "center" },
            { field: 'MaxCount', title: '设备数', align: "center" },
            { field: 'MaxDataCount', title: '数据数', align: "center" },
            { field: 'LastLoginIp', title: '上次登录IP', align: "center" },
            {
                field: 'LastLoginTime', title: '上次登录时间', align: 'center', templet: function (d) {
                    if (d.LastLoginTime != d.AddTime) {
                        return '<span>' + d.LastLoginTime + '</span>';
                    } else {
                        return '<span class="layui-blue">未登录</span>';
                    }
                }
            },
            {
                field: 'ExpireDate', title: '过期时间', align: 'center', templet: function (d) {
                    if (d.IsExpired) {
                        return '<span style="color:red;">' + d.ExpireDate + '</span>';
                    } else {
                        return '<span style="color:#1E9FFF;">' + d.ExpireDate + '</span>';
                    }
                }
            },
            { field: 'AddTime', title: '添加时间', align: 'center' },
            { title: '操作', width: 170, templet: '#userListBar', fixed: "right", align: "center" }
        ]]
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $("#btnSearchUser").on("click", function () {
        table.reload("userListTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                userState: $('#enable').val(),
                expire: $('#expire').val(),
                userName: $('#txtUserName').val()
            }
        })
    });

    //添加
    function addUser() {
        layui.layer.open({
            title: "新增用户",
            type: 1,
            btn: ['确定', '取消'],
            area: ['500px', '550px'],
            offset: '100px',
            content: $('#addUserDialog').html(),
            success: function (layero, index) {
                var htmls = [];
                scripts.forEach(item => {
                    htmls.push('<input type="checkbox" name="scripts" value="' + item.Id + '" title="' + item.Name + '">')
                });

                $('#scriptsDiv').append(htmls.join(''));
                form.render('checkbox');
                laydate.render({ elem: '#expireTime' });
            },
            yes: function (index, layero) {
                var userName = $('#userName').val();
                var password = $('#password').val();
                var expireTime = $('#expireTime').val();
                var maxCount = $('#maxCount').val();
                var maxDataCount = $('#maxDataCount').val();                
                var code = $('#code').val();
                var scripts = $('input[type="checkbox"]:checked');

                if (userName.length < 1 && userName.length > 16) {
                    layer.msg('用户名 1-16 位之间');
                    return;
                }

                if (password.length < 6 || password.length > 12) {
                    layer.msg('密码 6-12 位之间');
                    return;
                }

                if (expireTime.length < 1) {
                    layer.msg('请输入到期时间');
                    return;
                }

                if (maxCount.length < 1) {
                    layer.msg('请输入最大设备数量');
                    return;
                }

                if (maxDataCount.length < 1) {
                    layer.msg('请输入最大数据数量');
                    return;
                }

                if (code.length < 1) {
                    layer.msg('请输入设备验证码');
                    return;
                }

                if (scripts.length < 0) {
                    layer.msg('请选择用户脚本');
                    return;
                }

                var userScripts = [];

                for (var i = 0; i < scripts.length; i++) {
                    userScripts.push({ ScriptId: parseInt(scripts[i].value) });
                }

                $.post('/admin/user/add', {
                    userName: userName,
                    password: password,
                    expireDate: expireTime,
                    code: code,
                    maxCount: maxCount,
                    maxDataCount: maxDataCount,
                    userScripts: userScripts
                }, function (data) {
                    if (data.Code == 1) {
                        layer.close(index);
                        tableIns.reload({
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            where: {
                                userState: $('#enable').val(),
                                expire: $('#expire').val(),
                                userName: $('#txtUserName').val()
                            }
                        });
                    } else {
                        layer.msg(data.Msg);
                    }
                });
            }
        });
    }

    $("#btnAddUser").click(function () {
        addUser();
    })

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('userListTable'),
            data = checkStatus.data,
            keys = [];

        if (data.length > 0) {
            for (var i in data) {
                keys.push(data[i].UserName);
            }

            layer.confirm('确定删除？', { icon: 3, title: '提示信息', offset: '100px' }, function (index) {
                $.post('/admin/user/delete-users', {
                    ids: keys
                }, function (data) {
                    if (data.Code == 1) {
                        tableIns.reload({
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            where: {
                                userState: $('#enable').val(),
                                expire: $('#expire').val(),
                                userName: $('#txtUserName').val()
                            }
                        });
                        layer.close(index);
                    } else {
                        layer.msg(data.Msg);
                    }
                });
            })
        } else {
            layer.msg("请选择需要删除的用户");
        }
    })

    $('#btnGetCount').click(function () {
        if (websocketHeartbeatJs && websocketHeartbeatJs.ws && websocketHeartbeatJs.ws.readyState == 1) {
            websocketHeartbeatJs.send(JSON.stringify({ Command: 9999 }));
        } else {
            layer.msg('链接未就绪，请刷新页面重试');
        }
    });

    $('#btnShowNoticeDialog').click(function () {
        layer.prompt({
            formType: 2,
            value: '',
            offset: '165px',
            title: '即时通知'
        }, function (value, index, elem) {
            if (value.length >= 0) {
                if (websocketHeartbeatJs && websocketHeartbeatJs.ws && websocketHeartbeatJs.ws.readyState == 1) {
                    websocketHeartbeatJs.send(JSON.stringify({ Command: 9998, Data: value }));
                    layer.msg('已发送');
                } else {
                    layer.msg('链接未就绪，请刷新页面重试');
                }
            } else {
                layer.msg('消息为空');
            }
        });
    });

    //列表操作
    table.on('tool(userList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'del') { //删除
            layer.confirm('确定删除？', { icon: 3, title: '提示信息', offset: '100px' }, function (index) {
                $.post('/admin/user/delete', {
                    userName: data.UserName
                }, function (data) {
                    if (data.Code == 1) {
                        tableIns.reload({
                            page: {
                                curr: 1 //重新从第 1 页开始
                            },
                            where: {
                                userState: $('#enable').val(),
                                expire: $('#expire').val(),
                                userName: $('#txtUserName').val()
                            }
                        });
                        layer.close(index);
                    } else {
                        layer.msg(data.Msg);
                    }
                })
            });
        } else if (layEvent === 'scripts') {
            $.post('/admin/script/list-for-user', { userName: data.UserName }, function (res) {
                if (res.Code == 1) {
                    res.Data.forEach(function (item) {
                        item.LAY_CHECKED = item.WebPath == 'true';
                    });
                    layer.open({
                        title: '用户脚本',
                        btn: ['确定更新', '取消'],
                        type: 1,
                        area: '400px', //宽高
                        offset: '100px',
                        content: $('#userScriptDialog').html(),
                        success: function (layero, index) {
                            table.render({
                                elem: '#userScriptList',
                                cellMinWidth: 95,
                                page:true,
                                limit: 15,
                                limits: [15, 20],
                                id: "userScriptListTable",
                                cols: [[
                                    { type: 'checkbox' },
                                    { field: 'Name', title: '名称', align: 'center' },
                                    { field: 'VersionName', title: '版本', align: 'center' }
                                ]],
                                data: res.Data
                            })
                        },
                        yes: function (index, layero) {
                            var checkRow = table.checkStatus('userScriptListTable');
                            var scriptIds = [];
                            checkRow.data.forEach(function (item) {
                                scriptIds.push(item.Id);
                            });

                            $.post('/admin/script/update-user-scripts', { userName: data.UserName, scriptIds: scriptIds }, function (res) {
                                if (res.Code == 1) {
                                    layer.close(index);
                                } else {
                                    layer.msg(res.Msg);
                                }
                            });
                        }
                    });
                } else {
                    layer.msg(res.Msg);
                }
            });
        }
    });
})